package com.thinkingstar.iads.cs.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.thinkingstar.iads.common.config.BaseModule;
import com.thinkingstar.iads.common.config.Globals;
import com.thinkingstar.iads.common.enums.DesignContentsLibrary;
import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;

import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import com.thinkingstar.iads.common.utils.CommonDateUtil;
import com.thinkingstar.iads.common.utils.IdcardUtils;
import com.thinkingstar.iads.common.utils.InitSystemProperties;
import com.thinkingstar.iads.common.utils.PublicRequestUtil;
import com.thinkingstar.iads.cs.sys.entity.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.nutz.dao.*;
import org.nutz.dao.Chain;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@IocBean
@At("/private/sys/user")
@Filters({@By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class)})
public class UserModule extends BaseModule {

    private static final String PATH = "beetl:/projectRoot/sysCenter/users/";

    @Inject
    protected Dao dao;

    @At("")
    @Ok(PATH+"user.html")
    public void user(HttpSession session, HttpServletRequest req) {
        SysUser user = (SysUser) session.getAttribute("userSession");
        String unitid = user.getUnitid();
        req.setAttribute("unitid", unitid);
        /*   当前用户所属专业 start*/
        String majorid = user.getMajorid();
        req.setAttribute("majorid", majorid);
        /*  当前用户所属专业 end*/
    }

    @At
    @Ok("raw")
    public String search(@Param("username") String username, @Param("userid") int userid) {
        if (!Strings.isBlank(username)) {
            return Json.toJson(daoCtl.list(dao, SysUser.class, Cnd.where("realname", "like", "%" + username + "%")));
        } else if (userid > 0) {
            return Json.toJson(daoCtl.list(dao, SysUser.class, Cnd.where("id", "=", userid)));
        }
        return "";
    }

    /***
     *  获取专业树
     * @param id
     * @return
     */
    @At
    @Ok("raw")
    public String tree(@Param("id") String id) {
        id = Strings.sNull(id);
        List<Object> array = new ArrayList<Object>();
        if ("".equals(id)) {
            Map<String, Object> jsonroot = new HashMap<String, Object>();
            jsonroot.put("id", "");
            jsonroot.put("pId", "0");
            jsonroot.put("name", "机构列表");
            jsonroot.put("checked", false);
            jsonroot.put("nocheck", true);
            jsonroot.put("url", "javascript:list(\"\")");
            jsonroot.put("target", "_self");
            jsonroot.put("icon", "images/icons/icon042a1.gif");
            array.add(jsonroot);
        }

        /* 专业列表 start*/
        Criteria cri = Cnd.cri();
        cri.where().and("id", "like", id + "____");

        List<SysMajor> majorList = null;
        String majorSql = "select * from dc_sys_major where id like" + "____";
        Sql sql = Sqls.create(majorSql);
        majorList = daoCtl.list(dao, SysMajor.class, cri);
        int i = 0;
        for (SysMajor major : majorList) {
            String pid = major.getPid();
            int num = daoCtl.getRowCount(dao, SysMajor.class,
                    Cnd.wrap("id like '" + major.getId() + "____'"));
            if (!StringUtils.isNotBlank(pid)) {
                pid = "0";
            }
            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("id", major.getId());
            obj.put("pId", pid);
            obj.put("name", major.getName());
            obj.put("url", "javascript:list(\"" + major.getId() + "\")");
            obj.put("target", "_self");
            obj.put("isParent", num > 0);
            array.add(obj);
            i++;
        }
        return Json.toJson(array);
    }

    /*获取专业名称*/
    @At
    @Ok("raw")
    public String getmajorname(@Param("majorid") String majorid) {
        if ("".equals(majorid)) return "所有机构";
        return daoCtl.detailByName(dao, SysMajor.class, majorid).getName();
    }

    @At
    @Ok("raw")
    public String getuname(@Param("unitid") String unitid) {
        if ("".equals(unitid)) return "所有机构";
        return daoCtl.detailByName(dao, SysUnit.class, unitid).getName();
    }

    @At
    @Ok("raw")
    public String list(@Param("majorid") String majorid,
                           @Param("page_num") int curPage, @Param("page_size") int pageSize,
                           @Param("SearchUserName") String SearchUserName, @Param("lock") String lock) {
        SysUser user = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
//        Criteria cri = Cnd.cri();
//        cri.where().and("IS_DELETE", "=", 0);
        Sql sql = Sqls.create("select roleid from dc_sys_user_role where userid=@userid");
        sql.params().set("userid", user.getId());

        String userSql = "select su.* from dc_sys_user su left join dc_sys_major major on su.id=major.userid where 1=1";
        if (!"".equals(majorid)) {
            userSql = userSql + " and major.majorid='" + majorid + "'";
        } else {
            userSql = "select su.* from dc_sys_user su  where 1=1";
        }
        if ("1".equals(lock)) {
//            cri.where().and("state", "=", 1);
            userSql = userSql + " and su.state='1'";
        }
        if (!Strings.isBlank(SearchUserName)) {
            userSql = userSql + " and (su.loginname like %'" + SearchUserName + "'% or realname like %'" + SearchUserName + "'%)";
        }
//        cri.getOrderBy().asc("id");
        userSql = userSql + " order by su.id asc";
        Sql executeSql = Sqls.create(userSql);
        return daoCtl.listPageJsonSql(dao, executeSql, curPage, pageSize);
       /* return daoCtl.listPageJson(dao, SysUser.class, curPage,
                pageSize, cri);*/
    }

    @At
    @Ok("raw")
    public String listUserByUnitId(@Param("unitId") String unitId,
                       @Param("page_num") int curPage, @Param("page_size") int pageSize,
                       @Param("SearchUserName") String SearchUserName, @Param("lock") String lock) {
        SysUser user = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
//        Criteria cri = Cnd.cri();
//        cri.where().and("IS_DELETE", "=", 0);
        Sql sql = Sqls.create("select roleid from dc_sys_user_role where userid=@userid");
        sql.params().set("userid", user.getId());

        String userSql = "select su.* from dc_sys_user su left join dc_sys_unit unit on su.unitid=unit.id where 1=1";
        if (!"".equals(unitId)) {
            userSql = userSql + " and unit.id='" + unitId + "'";
        } else {
            userSql = "select su.* from dc_sys_user su  where 1=1";
        }
        if ("1".equals(lock)) {
//            cri.where().and("state", "=", 1);
            userSql = userSql + " and su.state='1'";
        }
        if (!Strings.isBlank(SearchUserName)) {
            userSql = userSql + " and (su.loginname like BINARY  \'%" + SearchUserName + "%\' or realname like BINARY  \'%" + SearchUserName + "%\')";
        }
        //删除的账户应该剔除掉不显示
//        cri.getOrderBy().asc("id");
        userSql = userSql + " and is_delete=0 order by su.id asc";
        Sql executeSql = Sqls.create(userSql);
        batchPullUserToDdddl();
        return daoCtl.listPageJsonSql(dao, executeSql, curPage, pageSize);
    }


    @At
    @Ok("raw")
    public void toadd(@Param("unitId") String unitId) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("userSession");

        Condition sql;
        Condition sqlunit;
        Condition sqlrole;
        List<SysRole> list = null;
        List<SysRole> rolelist = null;
//        List<SysUnit> unitlist = null;
        int sysrole = 0;
        if (user.getRolelist().contains(2)) // 判断是否为系统管理员角色
        {
            sysrole = 1;
        }
//        unitlist = daoCtl.list(dao, SysUnit.class, sqlunit);
        SecurityUtils.getSubject().getSession().setAttribute("sysrole", sysrole);
        Hashtable<String, String> hm = new Hashtable<String, String>();
        List<Object> array = new ArrayList<Object>();
        Map<String, Object> jsonroot = new HashMap<String, Object>();
        jsonroot.put("id", "");
        jsonroot.put("pId", "0");
        jsonroot.put("name", "角色列表");
        jsonroot.put("checked", false);
        jsonroot.put("nocheck", true);
        jsonroot.put("open", true);
        jsonroot.put("icon", Globals.APP_BASE_NAME
                + "../images/icons/icon042a1.gif");
        sqlrole = Cnd.wrap("1=1");
        rolelist = daoCtl.list(dao, SysRole.class, sqlrole);
        for (int j = 0; j < rolelist.size(); j++) {

            SysRole roleobj = rolelist.get(j);
            Map<String, Object> jsonobj = new HashMap<String, Object>();
            jsonobj.put("id", String.valueOf(roleobj.getId()));
            jsonobj.put("pId", "");
            jsonobj.put("name", roleobj.getName());
            if (roleobj.getId() == 1) {
                jsonobj.put("checked", true);
            } else {
                jsonobj.put("checked", false);
            }
            jsonobj.put("url", "javascript:list(\"" + roleobj.getId()
                    + "\")");
            jsonobj.put("target", "_self");
            array.add(jsonobj);

        }
        array.add(jsonroot);
        SecurityUtils.getSubject().getSession().setAttribute("str", Json.toJson(array));
    }

    @At
    @Ok("raw")
    public boolean ajaxname(@Param("loginname") String loginname) {
        int res = daoCtl.getRowCount(dao, SysUser.class, Cnd.where("loginname", "=", loginname));
        return res > 0;
    }

    /**
     * 校验身份证号
     *
     * @param idCard
     * @return
     */
    @At
    @Ok("raw")
    public boolean ajaxIdCard(@Param("idCard") String idCard) {
        return IdcardUtils.validateCard(idCard);
    }

    public void updateDddlSysUser(SysUser sysUser,String type){
        String dddlUrl = InitSystemProperties.getDddlUrl();
        HashMap<String, String> map = new HashMap<>();
        if (type.equals("add")){
            dddlUrl = dddlUrl+"/userSourceApi/addUserSource";
        } else if (type.equals("update")){
            dddlUrl = dddlUrl+"/userSourceApi/updateUserSource";
        } else if (type.equals("delete")){
            dddlUrl = dddlUrl+"/userSourceApi/delUserSource";
        }
        map.put("realname",sysUser.getRealname());
        map.put("loginname", sysUser.getLoginname());
        map.put("salt", sysUser.getSalt());
        map.put("password", sysUser.getPassword());
        map.put("user_source", "jwdcjs");
        map.put("is_available", sysUser.getIs_available());
        map.put("state", Integer.toString(sysUser.getState()));
        map.put("is_delete", sysUser.getIs_delete());
        String result_strs =  PublicRequestUtil.setPostRequestURL(dddlUrl, map);
        if(StringUtils.isNotBlank(result_strs)){
            JSONObject parse = JSON.parseObject(result_strs);
            System.out.println("dddlUrl======"+dddlUrl+"=======result===="+parse.get("message"));
        }
    }

    /**用户数据批量同步到 单点登录里 只执行一次*/
    public void batchPullUserToDdddl(){
        String dddlUrl = InitSystemProperties.getDddlUrl()+"/userSourceApi/addUserSource";
        Condition c = Cnd.where("is_delete", "=", "0").and("is_available","=","1");
        List<SysUser> list = daoCtl.list(dao,SysUser.class, c);
        for(int i=0;i<list.size();i++){
            SysUser sysUser = list.get(i);
            HashMap<String, String> map = new HashMap<>();
            map.put("loginname", sysUser.getLoginname());
            map.put("salt", sysUser.getSalt());
            map.put("password", sysUser.getPassword());
            map.put("realname",sysUser.getRealname());
            map.put("user_source", "jwdcjs");
            map.put("is_available", "1");
            map.put("is_delete", "0");
            String result_strs =  PublicRequestUtil.setPostRequestURL(dddlUrl, map);
            if(StringUtils.isNotBlank(result_strs)){
                JSONObject parse = JSON.parseObject(result_strs);
                System.out.println("dddlUrl======"+dddlUrl+"=======result===="+parse.get("message"));
            }
        }
    }

    @At
    @Ok("raw:json")
    public boolean add(@Param("..") SysUser user) {
        SysUser result = null;
        try {
//            String[] ids = StringUtils.split(checkids, ",");
//            String majorIds = user.getMajorid();
//            String[] majorArr = majorIds.split(",");
            RandomNumberGenerator rng = new SecureRandomNumberGenerator();
            String salt = rng.nextBytes().toBase64();
            String hashedPasswordBase64 = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
            user.setPassword(hashedPasswordBase64);
            user.setSalt(salt);
            user.setLogintime(CommonDateUtil.getDateTime());
            user.setIs_available("1");
            user.setIs_delete("0");
            result = daoCtl.addT(dao, user);
            updateDddlSysUser(user,"add");
//            if (result != null) {
//                for (int i = 0; i < ids.length && (!"".equals(ids[0])); i++) {//用户角色关联表
//                    SysUserRole syr = new SysUserRole();
//                    syr.setUserid(result.getId());
//                    syr.setRoleid(NumberUtils.toInt(Strings.sNull(ids[i])));
//                    daoCtl.add(dao, syr);
//                }
//                SysUserMajor smajor = null;
//                for (int i = 0; i < majorArr.length; i++) {//用户专业关联表
//                    smajor = new SysUserMajor();
//                    smajor.setUserid(result.getId());
//                    smajor.setMajorid(majorArr[i]);
//                    daoCtl.add(dao, smajor);
//                }
                return true;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    @At
    @Ok("raw")
    public void toupdate(@Param("userid") long userid,
                         HttpSession session, HttpServletRequest req) {

        SysUser obj = daoCtl.detailById(dao, SysUser.class, userid);

        SysMajor major = daoCtl.detailByName(dao, SysMajor.class, obj.getMajorid());
        req.setAttribute("obj", obj);

        req.setAttribute("major", major);
        RandomNumberGenerator rng = new SecureRandomNumberGenerator();
        String salt = rng.nextBytes().toBase64();
        String hashedPasswordBase64 = new Sha256Hash(obj.getPassword(), salt, 1024).toBase64();
        obj.setPassword(hashedPasswordBase64);
        SysUser user = (SysUser) session.getAttribute("userSession");
        boolean self = false;

        Hashtable<String, String> hashrole = new Hashtable<String, String>();
        Sql sql = Sqls
                .create("select roleid,'wiz' from SYS_USER_ROLE where userid = "
                        + obj.getId());
        hashrole = daoCtl.getHTable(dao, sql);

        LinkedList<SysRole> list = null;
        LinkedList<SysRole> rolelist = null;
//        LinkedList<SysUnit> unitlist = null;
        int sysrole = 0;
//        Condition unitc;
        Condition rolec;
        if (user.getSysrole()) // 判断是否为系统管理员角色
        {
            sysrole = 1;
        }
        rolec = Cnd.wrap("1=1");
        req.setAttribute("sysrole", sysrole);
        Hashtable<String, String> hm = new Hashtable<String, String>();
        List<Object> array = new ArrayList<Object>();
        Map<String, Object> jsonroot = new HashMap<String, Object>();
        jsonroot.put("id", "");
        jsonroot.put("pId", "0");
        jsonroot.put("name", "角色列表");
        jsonroot.put("checked", false);
        jsonroot.put("nocheck", true);
        jsonroot.put("open", true);
        jsonroot.put("icon", Globals.APP_BASE_NAME
                + "../images/icons/icon042a1.gif");
        if (!"".equals(rolec)) {
            rolelist = (LinkedList<SysRole>) daoCtl.list(dao, SysRole.class,
                    rolec);
            for (int j = 0; j < rolelist.size(); j++) {

                SysRole roleobj = rolelist.get(j);
                Map<String, Object> jsonobj = new HashMap<String, Object>();
                jsonobj.put("id", String.valueOf(roleobj.getId()));
                jsonobj.put("pId", "");
                jsonobj.put("name", roleobj.getName());
                if (!"".equals(Strings.sNull(hashrole.get(String
                        .valueOf(roleobj.getId()))))) {
                    if (self) {
                        jsonobj.put("chkDisabled", true);
                    }
                    jsonobj.put("checked", true);
                } else {
                    jsonobj.put("checked", false);
                }
                array.add(jsonobj);

            }
        }
        array.add(jsonroot);
        req.setAttribute("str", Json.toJson(array));
    }

    @At
    @Ok(PATH+"grantUser.html")
    public void grantUser(@Param("userid") long userid,
                          HttpSession session, HttpServletRequest req) {
    	/*
        SysUser user = (SysUser) session.getAttribute("userSession");
        return daoCtl.detailById(dao, SysUser.class, user.getId());
        */
        SysUser obj = daoCtl.detailById(dao, SysUser.class, userid);
        SysUnit unit = daoCtl.detailByName(dao, SysUnit.class,
                obj.getUnitid());
        req.setAttribute("obj", obj);
        req.setAttribute("unit", unit);
    }

    @At
    @Ok("raw")
    public boolean userRoleAdd(@Param("userid") long userid, @Param("checkids") String roleids,
                               HttpServletRequest req) {
        /*绑定角色前先删除已有角色*/
        List<PersonalSpecialityRel> personalSpecialityList = dao.query(PersonalSpecialityRel.class, Cnd.where("PersonID", "=", String.valueOf(userid)));//根据用户id查询权限
        if (personalSpecialityList != null) {
            for (PersonalSpecialityRel personalSpecialityRel : personalSpecialityList) {
                dao.delete(personalSpecialityRel);
            }
        }
        if (roleids != null && roleids.length() > 0) {
            String[] rids = roleids.split(",");
            PersonalSpecialityRel personalSpeciality = null;
            for (int i = 0; i < rids.length; i++) {
                personalSpeciality = new PersonalSpecialityRel();
                personalSpeciality.setAuthorityId(rids[i]);
                personalSpeciality.setPersonID(String.valueOf(userid));
                dao.insert(personalSpeciality);
            }
        }
        return true;
    }

    /*    查询人员所属角色tree
     * @param id 机构id
     * */
    @At
    @Ok("raw")
    public String roleTree(@Param("userid") long userid, HttpSession session) {
        List<DesignContentsLibrary> allList = new ArrayList<DesignContentsLibrary>();
        List<DesignContentsLibrary> categorys = DesignContentsLibrary.finAllCategorys();//设计类别
        List<DesignContentsLibrary> specialitys = DesignContentsLibrary.finAllSpecialitys();//专业
        List<DesignContentsLibrary> items = DesignContentsLibrary.finAllItems();//设计内容
        allList.addAll(categorys);
        allList.addAll(specialitys);
        allList.addAll(items);
        /*根据userId查询其所属部门*/
        SysUser obj = daoCtl.detailById(dao, SysUser.class, userid);
        Map<String, Object> authorityMap = new HashMap<String, Object>();//当前部门的权限id集合
        /*查询其权限(所属部门以及人员)*/
        if (obj != null) {
            List<DeptSpecialityRel> deptSpecialityList = dao.query(DeptSpecialityRel.class, Cnd.where("DeptID", "=", obj.getUnitid()));//根据部门id查询权限
            if (deptSpecialityList != null) {
                for (DeptSpecialityRel deptSpecialityRel : deptSpecialityList) {
                    authorityMap.put(deptSpecialityRel.getAuthorityId(), null);
                }
            }
            List<PersonalSpecialityRel> personalSpecialityList = dao.query(PersonalSpecialityRel.class, Cnd.where("PersonID", "=", userid));//根据人员id查询权限
            if (personalSpecialityList != null) {
                for (PersonalSpecialityRel personalSpecialityRel : personalSpecialityList) {
                    authorityMap.put(personalSpecialityRel.getAuthorityId(), null);
                }
            }
        }
        List<Object> treearray = new ArrayList<Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", null);
        map.put("pId", 0);
        map.put("name", "定责列表");
        map.put("icon", Globals.APP_BASE_NAME
                + "../images/icons/icon042a1.gif");
        map.put("nocheck", true);
        treearray.add(map);
        for (DesignContentsLibrary t : allList) {
            Map<String, Object> jsonroot = new HashMap<String, Object>();
            if (authorityMap.containsKey(t.getCode())) {
                jsonroot.put("id", t.getCode());
                jsonroot.put("pId", t.getPid());
                jsonroot.put("name", t.getName());
                jsonroot.put("checked", true);
            } else {
                jsonroot.put("id", t.getCode());
                jsonroot.put("pId", t.getPid());
                jsonroot.put("name", t.getName());
            }
            treearray.add(jsonroot);
        }

        return Json.toJson(treearray);
    }


    @At
    @Ok("raw")
    public boolean updateSingle(@Param("..") SysUser user,
                          @Param("oldloginname") String oldloginname) {
        boolean result = false;
        try {
            if (!Strings.isBlank(user.getPassword())) {
                RandomNumberGenerator rng = new SecureRandomNumberGenerator();
                String salt = rng.nextBytes().toBase64();
                String hashedPasswordBase64 = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
                user.setPassword(hashedPasswordBase64);
                user.setSalt(salt);
            } else {
                user.setPassword(null);
            }
            user.setLogintime(CommonDateUtil.getDateTime());
            result = daoCtl.update(dao, user);
            updateDddlSysUser(user,"update");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
        }
    }



    @At
    public boolean update(@Param("..") SysUser user,
                          @Param("checkids") String checkids,
                          @Param("oldloginname") String oldloginname) {
        boolean result = false;
        try {
            String[] ids = StringUtils.split(checkids, ",");
            if (!Strings.isBlank(user.getPassword())) {
                RandomNumberGenerator rng = new SecureRandomNumberGenerator();
                String salt = rng.nextBytes().toBase64();
                String hashedPasswordBase64 = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
                user.setPassword(hashedPasswordBase64);
                user.setSalt(salt);
            } else {
                user.setPassword(null);
            }
            user.setLogintime(CommonDateUtil.getDateTime());
            result = daoCtl.update(dao, user);
            updateDddlSysUser(user,"update");
            if (result) {
                daoCtl.delete(dao, "dc_sys_user_role",
                        Cnd.where("userid", "=", user.getId()));
                for (int i = 0; i < ids.length && (!"".equals(ids[0])); i++) {
                    SysUserRole syr = new SysUserRole();
                    syr.setUserid(user.getId());
                    syr.setRoleid(NumberUtils.toInt(Strings.sNull(ids[i])));
                    daoCtl.add(dao, syr);
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
        }
    }


    @At
    public int delete(@Param("ids") String ids) {
        int result = 0;
        String[] id = StringUtils.split(ids, ",");
        result = daoCtl.deleteByIdsLongIS(dao, SysUser.class, org.nutz.dao.Chain.make("IS_DELETE", 1), id);
        if (result > 0) {
            Sql sql = Sqls.create("delete from dc_sys_user_role where userid=@userid");
            for (int i = 0; i < id.length; i++) {
                SysUser sysUser = daoCtl.detailById(dao,SysUser.class,NumberUtils.toLong(Strings.sNull(id[i])));
                updateDddlSysUser(sysUser,"delete");
                sql.params().set("userid", NumberUtils.toLong(Strings.sNull(id[i])));
                sql.addBatch();
            }
            dao.execute(sql);
        }
        return result;
    }

    @At
    public boolean lock(@Param("ids") String ids) {
        String[] id = StringUtils.split(ids, ",");
        boolean result = false;
        for (int i = 0; i < id.length; i++) {
            result = daoCtl.update(dao, SysUser.class, Chain.make("state", 1),
                    Cnd.where("id", "=", NumberUtils.toLong(Strings.sNull(id[i]))));
            SysUser sysUser = daoCtl.detailById(dao,SysUser.class,NumberUtils.toLong(Strings.sNull(id[i])));
            updateDddlSysUser(sysUser,"update");
        }
        return result;
    }

    @At
    public boolean unlock(@Param("ids") String ids) {
        String[] id = StringUtils.split(ids, ",");
        boolean result = false;
        for (int i = 0; i < id.length; i++) {
            result = daoCtl.update(dao, SysUser.class, Chain.make("state", 0),
                    Cnd.where("id", "=", NumberUtils.toLong(Strings.sNull(id[i]))));
            SysUser sysUser = daoCtl.detailById(dao,SysUser.class,NumberUtils.toLong(Strings.sNull(id[i])));
            updateDddlSysUser(sysUser,"update");
        }
        return result;

    }

    /**
     * 个人信息
     */
    @At
    @Ok(PATH+"userInfo.html")
    public SysUser info(HttpSession session) {
        SysUser user = (SysUser) session.getAttribute("userSession");
        return daoCtl.detailById(dao, SysUser.class, user.getId());
    }

    /**
     * 更新个人信息
     */
    @At
    @Ok("raw")
    public String updateInfo(@Param("..") SysUser user,
                             @Param("userid") String userid, @Param("password2") String pass,
                             @Param("oldpassword") String oldpassword) {
        SysUser olduser = daoCtl.detailByName(dao, SysUser.class, "id",
                userid);
        boolean relogin = false;
        String hashedPasswordBase64 = new Sha256Hash(oldpassword, olduser.getSalt(), 1024).toBase64();
        if (hashedPasswordBase64.equals(olduser.getPassword())) {
            if (!"".equals(pass)) {
                relogin = true;
                RandomNumberGenerator rng = new SecureRandomNumberGenerator();
                String salt = rng.nextBytes().toBase64();
                String hashedPasswordBase = new Sha256Hash(user.getPassword(), salt, 1024).toBase64();
                user.setPassword(hashedPasswordBase);
                olduser.setPassword(hashedPasswordBase);
                olduser.setSalt(salt);
            }
            if (!olduser.getLoginname().equals(user.getLoginname())) {
                relogin = true;
            }
            olduser.setLoginname(user.getLoginname());
            olduser.setRealname(user.getRealname());
            olduser.setDescript(user.getDescript());
            olduser.setPosition(user.getPosition());
            olduser.setAddress(user.getAddress());
            olduser.setTelephone(user.getTelephone());
            olduser.setMobile(user.getMobile());
            olduser.setEmail(user.getEmail());
            olduser.setLinkqq(user.getLinkqq());
            olduser.setLinkweb(user.getLinkweb());
            boolean up = daoCtl.update(dao, olduser);
            updateDddlSysUser(olduser,"update");
            if (up && relogin) {
                return "relogin";
            } else if (up) {
                return "true";
            } else {
                return "false";
            }
        } else {
            return "error";
        }

    }
}
